package com.zhixi.controller;

import com.zhixi.pojo.User;
import com.zhixi.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(path = "/user")
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 查询所有的用户信息
     *
     * @return
     */
    @RequestMapping(path = "/list")
    public String list(Model model) {
        //调用业务层查询数据
        List<User> users = userService.list();
        //将用户数据保存到model
        model.addAttribute("users", users);
        //返回视图名称
        return "list";
    }

    /**
     * 添加用户信息
     *
     * @param user
     * @return
     */
    @RequestMapping(path = "/add")
    public String add(User user) {
        userService.add(user);
        return "redirect:/user/list";
    }

    /**
     * 根据id查询用户详情
     *
     * @param id
     * @return 查询到的用户
     */
    @RequestMapping(path = "/findById")
    public String findById(Integer id, Model model) {
        //调用业务层查询数据
        User user = userService.findById(id);
        //将数据保存到model
        model.addAttribute("user", user);
        //返回视图
        return "update";
    }

    /**
     * 根据主键更新数据
     *
     * @param user
     * @return
     */
    @RequestMapping(path = "/update")
    public String update(User user) {
        //调用业务层更新数据
        userService.update(user);
        //返回视图
        return "redirect:/user/list";
    }

    /**
     * 根据id删除数据
     *
     * @param id
     * @return
     */
    @RequestMapping(path = "/deleteById")
    public String deleteById(Integer id) {
        //调用业务层删除数据
        userService.deleteById(id);
        //返回视图
        return "redirect:/user/list";
    }
}
